package com.qdxwx.manage.controller.course;

import com.alibaba.fastjson2.JSON;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.AliyunUtils;
import com.qdxwx.common.utils.BaJiaYunUtils;
import com.qdxwx.common.utils.HttpUtils;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.manage.controller.BaseController;
import com.qdxwx.models.enums.WebsiteProfileType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 知识点的基本信息Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/course/node/upload")
public class CourseNodeUploadController extends BaseController {

    @Autowired
    private WebsiteProfileService websiteProfileService;

    /**
     * 阿里云上传视频
     */
    @RequestMapping("/aliyun.json")
    @ResponseBody
    public AjaxResult aliyunUpload(MultipartFile file, String title) throws Exception {
        if (TKString.isEmpty(title)) {
            return AjaxResult.error("请输入章节名称");
        }
        if (file.isEmpty()) {
            return AjaxResult.error("请上传视频文件");
        }
        Map<String, Object> aliyunMap = websiteProfileService.getMap("aliyun");
        String videoId = AliyunUtils.uploadStream(aliyunMap.get("accessKeyId").toString(), aliyunMap.get("accessKeySecret").toString(), title, file.getOriginalFilename(), file.getInputStream());
        if (TKString.isEmpty(videoId)) {
            return AjaxResult.error("上传失败");
        }
        return AjaxResult.success(videoId);
    }

    /**
     * 百家云上传视频
     */
    @RequestMapping("/baijiayun.json")
    @ResponseBody
    public Map<String, Object> getUploadUrl(HttpServletRequest request) {
        String fileName = TKString.queryKey(request.getParameter("title"));
        if (TKString.isEmpty(fileName)) {
            return AjaxResult.error("请先输入章节标题");
        }
        Map<String, Object> baijiayunMap = websiteProfileService.getMap(WebsiteProfileType.baiJiaYun.toString());
        SortedMap<String, String> message = new TreeMap<>();
        message.put("file_name", fileName);
        message.put("definition", "2,4,8");
        message.put("timestamp", (System.currentTimeMillis() / 1000) + "");
        message.put("sign", BaJiaYunUtils.createSign(message, baijiayunMap));
        String requeMsg = HttpUtils.doPost(baijiayunMap.get("partnerDomain") + "openapi/video/getUploadUrl", message);
        return JSON.parseObject(requeMsg, Map.class);
    }
}
